package com.jiaming.employee.account.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jiaming.employee.account.bean.pojo.Account;
import com.jiaming.employee.account.bean.vo.LoginDataVO;
import com.jiaming.employee.account.bean.vo.LoginVo;
import com.jiaming.employee.account.service.IAccountService;
import com.jiaming.employee.common.exception.ApiException;
import com.jiaming.employee.common.exception.InvalidTokenException;
import com.jiaming.employee.common.response.ResultCodeEnum;
import com.jiaming.employee.common.response.ResultVO;
import com.jiaming.employee.common.utils.JwtInfo;
import com.jiaming.employee.common.utils.JwtUtil;
import com.jiaming.employee.common.utils.SecureKeyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dragon
 * @create 2021-04-13 18:06
 */
@Api(tags = "登录API接口文档")
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    IAccountService accountService;

    @PostMapping("login")
    @ApiOperation(value = "登录",notes = "登录调用的接口")
    public ResultVO<LoginDataVO> login(@RequestBody @Valid LoginVo loginVo){

        String s = SecureUtil.md5(loginVo.getLoginPwd());
        loginVo.setLoginPwd(s);
        Account account = accountService.getLogin(loginVo);
        if (account == null) {
            throw new ApiException("账户或密码不正确!");
        }
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setId(account.getId());
        jwtInfo.setLoginName(account.getLoginName());
        jwtInfo.setExpiredDate(DateUtil.offset(new Date(), DateField.MINUTE,10));
        String token = JwtUtil.createSign(jwtInfo);

        LoginDataVO loginDataVO = new LoginDataVO();
        loginDataVO.setLoginName(account.getLoginName());
        loginDataVO.setAccessToken(token);
        return new ResultVO<>(ResultCodeEnum.SUCCESS,loginDataVO);
    }
}
